package com.hand.demo.app.service.impl;

import com.hand.demo.domain.entity.LmExample;
import com.hand.demo.domain.repository.LmExampleRepository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.stream.Collectors;
import io.choerodon.mybatis.domain.AuditDomain;
import java.util.Map;

import org.springframework.stereotype.Service;
import com.hand.demo.app.service.LmExampleService;
import java.util.List;


/**
 * 应用服务默认实现
 *
 * @author xiuhong.chen@hand-china.com 2023-09-23 11:33:24
 */
@Service
public class LmExampleServiceImpl implements LmExampleService {
                                
    @Autowired
    private LmExampleRepository lmExampleRepository;


    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<LmExample> batchSave(List<LmExample> lmExampleList) {
        Map<AuditDomain.RecordStatus, List<LmExample>> statusMap = lmExampleList.stream().collect(Collectors.groupingBy(LmExample::get_status));
        // 删除
        if (statusMap.containsKey(AuditDomain.RecordStatus.delete)) {
            List<LmExample> deleteList = statusMap.get(AuditDomain.RecordStatus.delete);
            lmExampleRepository.batchDeleteByPrimaryKey(deleteList);
        }
        // 更新
        if (statusMap.containsKey(AuditDomain.RecordStatus.update)) {
            List<LmExample> updateList = statusMap.get(AuditDomain.RecordStatus.update);
            updateList.forEach(item -> {
                // TODO: 唯一性校验
                lmExampleRepository.updateByPrimaryKeySelective(item);
            });
        }
        // 新增
        if (statusMap.containsKey(AuditDomain.RecordStatus.create)) {
            List<LmExample> createList = statusMap.get(AuditDomain.RecordStatus.create);
            createList.forEach(item -> {
                // TODO: 唯一性校验
                lmExampleRepository.insertSelective(item);
            });
        }
        return lmExampleList;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public LmExample save(LmExample lmExample) {
        //保存
        if (lmExample.getId() == null) {
            lmExampleRepository.insertSelective(lmExample);
        } else {
            lmExampleRepository.updateOptional(lmExample,
                    LmExample.FIELD_NAME
            );
        }

        return lmExample;
    }
}
